<template>
  <view class="grade">
    <action-bar :options="navOptions"></action-bar>
    <view class="box">
      <view class="grade-box" v-for="(item, index) in list" :key="index">
        <!-- 单个 -->
        <view class="grade-box-type" @click="navTo(item, index)">
          <view class="grade-box-type-span">
            <view class="flex flex-direction" style="justify-content: center;">
              <span class="name ">{{ item.wbName }}</span>
              <span class="name " style="
                font-size: 20rpx;
                color: red;
              ">({{ item.staffName }})</span>
            </view>
            <!--已完成-->
            <image v-if="item.state == '3'" class="grade-box-type-span-image" src="/static/implement.png" mode="" />
            <!--部分完成-->
            <image v-if="item.state == '2'" class="grade-box-type-span-image" src="/static/incomplete.png" mode="" />

          </view>
          <view class="cuIcon-right" style="line-height:100rpx"> </view>
        </view>
      </view>

      <!-- 提示 -->
      <view class="grade-box-tip">
        <view class="grade-box-tip-span">提示:</view>
        <span>蓝色图标代表已完成，灰色图标代表部分完成，无图标代表未执业</span>
      </view>

      <view style="height:100rpx"></view>
    </view>

    <view class="btn-sure" v-if="isConfirm == '0' && !dontBtn" @click="btn_sure">
      <view class="btn">确认任务</view>
    </view>
  </view>
</template>

<script>
import {
  baseImgUrl,
  baseApiUrl
} from "@/config.js";
import { mapState, mapMutations } from "vuex";

let networkTypes = true;
export default {
  computed: {
    ...mapState({
      startTime: state => state.manage.startTime,
      endTime: state => state.manage.endTime,
      manageList: state => state.manage.manageList,
    }),
  },
  data() {
    return {
      baseImgUrl: baseImgUrl,
      baseApiUrl: baseApiUrl,
      navOptions: {
        statusBar: "dark",
        left: {
          icon: "back",
        },
        center: {
          title: "执业内容",
        },
      },
      list: [], // 列表内容
      taskId: "", // 任务id
      staffId: null, // 上个页面带过来的项目负责人id：staffId
      isConfirm: null, // 上个页面带过来代表是否已经确认过这个任务的字段
      loginStaffId: null, // 上个页面带过来代表当前登录人的staffId

      // 进入页面时，就获取当前执业人员是否满足中级及中级以上人员要求；当为true时，代表满足，可以进行下一步，如果为flase时，代表不满足，不能执行下一步
      meetJudgmentLevel: null,

      stateIndex: 0, // 记录提交成功次数，如果与提交次数不匹配时，应提示提交失败，若与提交次数匹配时，则提示提交成功
      uploadTime: 0, // 记录需要提交的次数

      uploadIndex: null, // 记录点击提交时的下标，方便提交成功后清除提交两个字

      design: null, // 该字段代表是开始执业还是确认任务(为'confirm'时代表确认任务confirm；为'practice'时代表开始执业)
      dontBtn: false, // 从查看进度按钮进入的页面时，无需操作按钮

      // setInterval: null, // 定时器
    };
  },
  onLoad(options) {
    let that = this
    that.design = options.design
    this.staffId = options.staffId || null;
    this.isConfirm = options.isConfirm || null;
    this.loginStaffId = options.loginStaffId || null;
    this.dontBtn = options.dontBtn || false;
    // 获取任务id
    this.taskId = this.$store.state.unitTask.taskId;
    // 判断是否再执业时间内
    let startTime = that.$store.state.manage.startTime
    let endTime = that.$store.state.manage.endTime
    // 获取当前时间戳
    let newListTime = new Date().getDate()
    if (startTime && endTime) {
      let newStart = startTime.split('-')[2] || 0
      let NewEnd = endTime.split('-')[2] || 0
      if (Number(newStart) > newListTime || newListTime > Number(NewEnd)) {
        that.design = 'confirm' // 若当前时间在执业计划时间外，直接将design字段改为确认任务状态
      }
    }
  },
  // onHide() {
  //   clearInterval(this.setInterval);
  // },
  // onUnload() {
  //   clearInterval(this.setInterval);
  // },
  onShow() {
    let that = this

    if (that.design != 'confirm') {
      // #ifdef MP-WEIXIN
      wx.enableAlertBeforeUnload({
        message: "确定所有数据都提交，是否返回？返回后未提交数据将清空！",
        complete: (e) => {
          console.log(e);
        }
      })
      // #endif
    }
    // 获取当前网络状态，当有网络时，则调用接口，若无网络则使用缓存数据
    networkTypes = navigator.onLine;
    if (networkTypes) {
      // 获取表单信息
      that.getForm();
      // 进入页面时，就获取当前执业人员是否为中级及中级以上人员(如果为项目负责人，则无需校验)
      that.getJudgmentLevel()
    } else {
      this.list = this.manageList
      this.$forceUpdate()
    }
  },
  methods: {
    // 获取只有自己需要执业的执业树
    Formatting(list) {
      let that = this
      let newList = []
      let oldList = list.map(item => {
        if (item.staffId) {
          item.staffId = item.staffId.split(',')
        }
        return item
      })
      oldList.forEach(item => {
        if (item.staffId && item.staffId.indexOf(that.loginStaffId) != '-1') {
          newList.push(item)
        }
      })
      return newList
    },
    // 获取表单信息
    getForm() {
      let that = this
      this.$store.dispatch("unitForm", this.taskId)
        .then((res) => {
          if (res && res.code === 200) {
            //! design=='practice'为开始执业按钮进入的，则查询出自己需要执业的部分执业树，反之design=='confirm'，需查询出全部执业树
            let list = []
            if (that.design == 'practice') {
              list = that.Formatting(res.data.wbDetailList)
            } else if (that.design == 'confirm') {
              list = res.data.wbDetailList
            } else {
              uni.showToast({
                title: "系统错误!",
                icon: "none",
                duration: 2000,
              });
              uni.navigateBack({
                delta: 1
              });
            }
            // 将过滤后的树缓存起来
            that.$store.commit('saveManageList', list)
            // 将执业的类型缓存起来(用于判断月度、季度、年度)
            that.$store.commit('savePractice', res.data.type)
            // 执业树
            that.list = list;
            // 该项目的项目id
            that.projectId = res.data.projectId;
          }
        })
    },
    addDate(date, days) {
      var d = new Date(date);
      d.setDate(d.getDate() + days);
      var m = d.getMonth() + 1;
      return d.getFullYear() + '-' + m + '-' + d.getDate();
    },
    navTo(item, index) {
      let that = this;
      //! 将需要执业的子项缓存起来
      this.$store.commit('saveTypeList', item.type)
      //! 将缓存起来的执业子项的下标缓存起来，等暂存的时候根据下标判断需要替换的数据是哪项
      this.$store.commit('saveTypeListIndex', index)
      this.$store.state.unitTask.wbName = item.wbName;
      //! design=='practice'为开始执业按钮进入的，反之design=='confirm'为确认任务进入的
      uni.navigateTo({
        url: "../../pages_workTableChild/manage/PracticeContent?design=" + that.design
      });
    },
    btn_sure() {
      let that = this;
      // let res = that.$store.state.manage.lastTime
      // let dist = that.addDate(res, 7)
      // 判断是否再执业时间内
      let startTime = that.$store.state.manage.startTime
      let endTime = that.$store.state.manage.endTime
      // let last = that.addDate(endTime, 7)
      // 获取当前时间戳
      let newListTime = new Date().getDate()

      if (startTime && endTime) {
        let newStart = startTime.split('-')[2] || 0
        let NewEnd = endTime.split('-')[2] || 0
        if (Number(newStart) > newListTime || newListTime > Number(NewEnd)) {
          uni.showModal({
            title: '警告',
            content: '当前执业时间不在计划执业时间内，无法提交执业内容',
          });
          return
        }
        //   if (new Date(dist) < new Date()) {
        //     uni.showModal({
        //       title: '警告',
        //       content: '已超出执业完成时间7天，无法确认任务',
        //     });
        //     return
        //   }
      }
      uni.showModal({
        title: "提示",
        content: "是否确认该任务!",
        success: function (res) {
          if (res.confirm) {
            let dist = {
              taskId: that.taskId,
            };
            that.$store.dispatch("confirmTaskList", dist).then((res) => {
              uni.showToast({
                title: "确认成功!",
                icon: "none",
                duration: 2000,
              });
              uni.reLaunch({
                url: "../../pages_workTableChild/manage/UnitTask",
              });
              that.$store.state.unitTask.projectLeader = null;
            });
          } else if (res.cancel) {
            uni.showToast({
              title: "取消确认!",
              icon: "none",
              duration: 2000,
            });
          }
        },
      });
    },

    // 进入页面时，就获取当前执业人员是否为中级及中级以上人员
    getJudgmentLevel() {
      if (this.isProjectHeads = '是') {
        this.meetJudgmentLevel = true
      } else {
        this.$store
          .dispatch("judgmentLevel", this.loginStaffId)
          .then((dist) => {
            if (
              dist.data.facilityOperators == "2" ||
              dist.data.facilityOperators == "3" ||
              dist.data.isResponsible == '是' ||
              this.isProjectHeads == '是'
            ) this.meetJudgmentLevel = true
          });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.grade {
  min-height: 100vh;

  .box {
    min-height: calc(100vh - 80rpx);
    background: $OVERALL_SITUATION_BACKGROUND_GRADIENT;
  }
}

.grade-box {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  &-type {
    width: calc(100% - 40rpx);
    min-height: 110rpx;
    background-color: #fff;
    border-radius: 20rpx;
    margin: 0 auto 24rpx;
    display: flex;
    justify-content: space-between;
    padding: 0 20rpx;

    &-span {
      font-size: 28rpx;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #333333;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;

      .name {
        width: 550rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      &-image {
        width: 28rpx;
        height: 28rpx;
        margin: 0 0 0 19rpx;
      }
    }
  }

  &-tip {
    display: flex;
    justify-content: flex-start;
    flex-direction: row;
    width: calc(100% - 48rpx);
    margin: 24rpx auto 0;
    font-size: 20rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #dc1010;

    &-span {
      width: 80rpx;
    }
  }
}

.btn-sure {
  width: 100%;
  position: fixed;
  bottom: 0;
  background: #fff;
  height: 100rpx;
  border-top: 1rpx solid #e5e5e5;

  .btn {
    margin: 10rpx auto;
    width: 710rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 28rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    background: $OVERALL_CONFIRM_BUTTON_COLOR;
    border-radius: 40rpx;
    color: #fff;
  }
}
</style>
